package com.zsr.common.utils.http;

import com.alibaba.fastjson2.JSONObject;
import lombok.extern.slf4j.Slf4j;
import okhttp3.*;
import org.springframework.http.HttpHeaders;

import java.io.IOException;
import java.util.Map;
import java.util.Objects;
import java.util.concurrent.TimeUnit;

/**
 * OkHttp工具类
 *
 * @author fanhang
 * @date 2022/4/3 10:42
 */
@Slf4j
public class OkHttpUtil {

    private OkHttpUtil() {
    }

    public static void main(String[] args) throws IOException {
        // 创建一个OkHttpClient对象
        OkHttpClient client = new OkHttpClient();

        // 创建一个Request.Builder对象，并添加header和url
        Request.Builder builder = new Request.Builder()
                .addHeader("Cookie", "_ati=1176000152475; _erpseid=4d45b1d4a32d5d8d1b249165426e68b09d479284; _scmcenseid=d7b803de786d17fce19da774dc685bf0a53e1c03; PHONE_CHECK_SUCCESS_565037375910400=2e2b7147-4efc-4c40-9819-49a4453d717f; _censeid=be4984582a426c82ef1e3888db1656ac930caa58; 3AB9D23F7A4B3C9B=YULKBTEVBC7PQ2SJGXL5UTY7ATCRJT4AG7CT7PSH6J5H56HLQLQXZQPJ2WX3QNDUBZA6WFCGH24UI5JQUZZMD3VNKY; _pdd_page_code=b3f9d7e8b0b147bfcb4e3034eb9c4e47f89980658f96; _pati=Thv4o2cONkQCWkUUasQxdAAt74Ey9Jyb; _pati_v=v2")
                .url("https://erpa.superboss.cc/report/trade/index?api_name=report_trade_index");

        // 创建一个Request对象并发送GET请求
        Response response = client.newCall(builder.build()).execute();
        System.out.println(response.body().string());
    }

    private final static MediaType MEDIA_TYPE = MediaType.get("application/json; charset=utf-8");

    private final static OkHttpClient OKHTTP_CLIENT = new OkHttpClient.Builder()
            .connectTimeout(15, TimeUnit.SECONDS)
            .readTimeout(15, TimeUnit.SECONDS)
            .writeTimeout(15, TimeUnit.SECONDS)
            .build();

    /**
     * POST请求
     *
     * @param url        地址
     * @param parameters JSON格式请求参数
     * @return 返回结果
     */
    public static String post(String url, String parameters, String token) {
        final RequestBody body = RequestBody.create(MEDIA_TYPE, parameters);
        final Request request = new Request.Builder()
                .url(url)
                .post(body)
                .header(HttpHeaders.CONTENT_TYPE, org.springframework.http.MediaType.APPLICATION_JSON_UTF8_VALUE)
                .header("x-acs-dingtalk-access-token", token)
                .build();
        try {
            final Response response = OKHTTP_CLIENT.newCall(request).execute();
            if (Objects.nonNull(response.body())) {
                return response.body().string();
            }
            throw new RuntimeException("OkHttpUtil.post. response body is empty, url: " + url + ", parameters: " + parameters);
        } catch (Exception e) {
            throw new RuntimeException("OkHttpUtil.post.EXCEPTION: " + e + ", url: " + url + ", parameters: " + parameters, e);
        }
    }

//    /**
//     * 快麦erppost请求
//     */
//    public static String kmPost(String url, String params) {
//        final RequestBody body = RequestBody.create(MEDIA_TYPE, params);
//        final Request request = new Request.Builder()
//                .url(url)
//                .post(body)
//                .header(HttpHeaders.CONTENT_TYPE, org.springframework.http.MediaType.MULTIPART_FORM_DATA_VALUE)
//                .build();
//        try {
//            final Response response = OKHTTP_CLIENT.newCall(request).execute();
//            if (Objects.nonNull(response.body())) {
//                return response.body().string();
//            }
//            throw new RuntimeException("OkHttpUtil.post. response body is empty, url: " + url + ", parameters: " + params);
//        } catch (Exception e) {
//            throw new RuntimeException("OkHttpUtil.post.EXCEPTION: " + e + ", url: " + url + ", parameters: " + params, e);
//        }
//    }

    /**
     * 金蝶get请求
     */
//    public static String jdGet(String url, Map<String, String> heads, Map<String, String> params) {
//        Headers.Builder headersBuilder = new Headers.Builder();
//        for (String key : heads.keySet()) {
//            headersBuilder.add(key, heads.get(key));
//        }
//        Headers headers = headersBuilder.build();
//
//        StringBuilder urlParams = new StringBuilder();
//        log.info("参数={}", JSONObject.toJSONString(params));
//        params.forEach((key, value) -> {
//            if (urlParams.length() > 0) {
//                urlParams.append('&');
//            }
//            urlParams.append(key).append('=').append(value);
//        });
//        if (urlParams.length() > 0) {
//            url += "?" + urlParams.toString();
//        }
//        final Request request = new Request.Builder().url(url).get().headers(headers).build();
//
//        try {
//            final Response response = OKHTTP_CLIENT.newCall(request).execute();
//            if (Objects.nonNull(response.body())) {
//                return response.body().string();
//            }
//            throw new RuntimeException("OkHttpUtil.get. response body is empty, url: " + url + ", parameters: " + params.toString());
//        } catch (Exception e) {
//            throw new RuntimeException("OkHttpUtil.get.EXCEPTION: " + e + ", url: " + url + ", parameters: " + params.toString(), e);
//        }
//    }

    /**
     * 金蝶post请求
     */
//    public static String jdPost(String url, Map<String, String> heads, String params) {
//        Headers.Builder headersBuilder = new Headers.Builder();
//        for (String key : heads.keySet()) {
//            headersBuilder.add(key, heads.get(key));
//        }
//        Headers headers = headersBuilder.build();
//
//        final RequestBody body = RequestBody.create(MEDIA_TYPE, params);
//
//        final Request request = new Request.Builder().url(url).post(body).headers(headers).build();
//
//        try {
//            final Response response = OKHTTP_CLIENT.newCall(request).execute();
//            if (Objects.nonNull(response.body())) {
//                return response.body().string();
//            }
//            throw new RuntimeException("OkHttpUtil.post. response body is empty, url: " + url + ", parameters: " + params.toString());
//        } catch (Exception e) {
//            throw new RuntimeException("OkHttpUtil.post.EXCEPTION: " + e + ", url: " + url + ", parameters: " + params.toString(), e);
//        }
//    }

    /**
     * del请求
     */
    public static String delete(String url, String parameters, String apimKey, String token) {
        final RequestBody body = RequestBody.create(MEDIA_TYPE, parameters);
        final Request request = new Request.Builder()
                .url(url)
                .delete()
                .header("Proxy-Authorization", "Bearer " + token)
                .header("Ocp-Apim-Subscription-Key", apimKey)
                .build();
        try {
            final Response response = OKHTTP_CLIENT.newCall(request).execute();
            if (Objects.nonNull(response.body())) {
                return response.body().string();
            }
            throw new RuntimeException("OkHttpUtil.delete. response body is empty, url: " + url + ", parameters: " + parameters);
        } catch (Exception e) {
            throw new RuntimeException("OkHttpUtil.delete.EXCEPTION: " + e + ", url: " + url + ", parameters: " + parameters, e);
        }
    }

    public static String get(String url) {
        final Request request = new Request.Builder()
                .url(url)
                .get()
                .build();
        try {
            final Response response = OKHTTP_CLIENT.newCall(request).execute();
            if (Objects.nonNull(response.body())) {
                return response.body().string();
            }
            throw new RuntimeException("OkHttpUtil.get. response body is empty, url: " + url);
        } catch (Exception e) {
            throw new RuntimeException("OkHttpUtil.get.EXCEPTION: " + e + ", url: " + url, e);
        }
    }


    public static String qwGet(String url, Map<String, Object> params) {
        StringBuilder urlParams = new StringBuilder();
        log.info("参数={}", JSONObject.toJSONString(params));
        if (params != null && !params.isEmpty()) {
            StringBuilder queryString = new StringBuilder();
            for (Map.Entry<String, Object> entry : params.entrySet()) {
                if (queryString.length() > 0) {
                    queryString.append("&");
                }
                queryString.append(entry.getKey()).append("=").append(entry.getValue());
            }
            url += "?" + queryString;
        }

        final Request request = new Request.Builder()
                .url(url)
                .get()
                .build();
        try {
            final Response response = OKHTTP_CLIENT.newCall(request).execute();
            if (Objects.nonNull(response.body())) {
                return response.body().string();
            }
            throw new RuntimeException("OkHttpUtil.get. response body is empty, url: " + url);
        } catch (Exception e) {
            throw new RuntimeException("OkHttpUtil.get.EXCEPTION: " + e + ", url: " + url, e);
        }
    }


    public static String qwPost(String url, Map<String, Object> params, JSONObject json) {
        // 将查询参数拼接到 URL
        log.info("参数={}", JSONObject.toJSONString(params));
        if (params != null && !params.isEmpty()) {
            StringBuilder queryString = new StringBuilder();
            for (Map.Entry<String, Object> entry : params.entrySet()) {
                if (queryString.length() > 0) {
                    queryString.append("&");
                }
                queryString.append(entry.getKey()).append("=").append(entry.getValue());
            }
            url += "?" + queryString;
        }

        // 创建请求体
        RequestBody body = RequestBody.create(MEDIA_TYPE, json.toJSONString());

        // 构建请求
        Request request = new Request.Builder()
                .url(url)
                .post(body)
                .build();

        // 执行请求
        try (Response response = OKHTTP_CLIENT.newCall(request).execute()) {
            if (!response.isSuccessful()) {
                throw new RuntimeException("Unsuccessful response: " + response.code() + ", url: " + url);
            }
            if (response.body() != null) {
                return response.body().string();
            }
            throw new RuntimeException("Response body is empty, url: " + url);
        } catch (IOException e) {
            String formattedParams = params != null ? params.toString() : "null";
            throw new RuntimeException(
                    String.format("OkHttpUtil.post.EXCEPTION: %s, url: %s, parameters: %s", e.getMessage(), url, formattedParams),
                    e
            );
        }
    }

    public static String post(String url, String parameters) {
        final RequestBody body = RequestBody.create(MEDIA_TYPE, parameters);
        final Request request = new Request.Builder()
                .url(url)
                .post(body)
                .build();
        try {
            final Response response = OKHTTP_CLIENT.newCall(request).execute();
            if (Objects.nonNull(response.body())) {
                return response.body().string();
            }
            throw new RuntimeException("OkHttpUtil.post. response body is empty, url: " + url + ", parameters: " + parameters);
        } catch (Exception e) {
            throw new RuntimeException("OkHttpUtil.post.EXCEPTION: " + e + ", url: " + url + ", parameters: " + parameters, e);
        }
    }

    public static String post(String url, String parameters, String appid, String signature) {
        final RequestBody body = RequestBody.create(MEDIA_TYPE, parameters);
        final Request request = new Request.Builder()
                .url(url)
                .post(body)
                .header("appid", appid)
                .header("signature", signature)
                .build();
        try {
            final Response response = OKHTTP_CLIENT.newCall(request).execute();
            if (Objects.nonNull(response.body())) {
                return response.body().string();
            }
            throw new RuntimeException("OkHttpUtil.post. response body is empty, url: " + url + ", parameters: " + parameters);
        } catch (Exception e) {
            throw new RuntimeException("OkHttpUtil.post.EXCEPTION: " + e + ", url: " + url + ", parameters: " + parameters, e);
        }
    }


}
